<?php
/**
 * 树型结构转换类
 * User: 91336
 * Date: 13-11-6
 * Time: 下午3:27
 */

class Tree
{
    public static function treeArray($data)
    {
        $result = array();
        //定义索引数组，用于记录节点在目标数组的位置，类似指针
        $p = array();

        foreach($data as $val)
        {
            if($val['pid'] == 0)
            {
                $i = count($result);
                $result[$i] = isset($p[$val['id']]) ? array_merge($val,$p[$val['id']]) : $val;
                $p[$val['id']] = & $result[$i];
            } else {
                $i = count($p[$val['pid']]['children']);
                $p[$val['pid']]['children'][$i] = $val;
                $p[$val['id']] = & $p[$val['pid']]['children'][$i];
            }
        }

        return $result;
    }

}